/*
 *  Copyright 2009 Jan-Kees van Andel.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.jkva.jsf.components.nonvalidatingcommand;

import javax.faces.component.UIInput;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * This PhaseListener is used to restore the required state of
 * the input fields that have been made not-required.
 * </p>
 * <p>
 * UIComponent lifecycle methods are not guaranteed to fire,
 * for example, when an Exception is thrown. This PhaseListener
 * is responsible for restoring a consistent component tree.
 * </p>
 * <p>
 * This PhaseListener also initializes the list of inputs so
 * the UIComponents don't have to.
 * </p>
 *
 * @author Jan-Kees van Andel
 */
public class RestoreRequiredPhaseListener implements PhaseListener {

    public static final ThreadLocal<List<UIInput>> inputsToRestore = new ThreadLocal<List<UIInput>>();

    /** {@inheritDoc} */
    public void beforePhase(PhaseEvent event) {
        // Initialize the list early
        if (event.getPhaseId().equals(PhaseId.APPLY_REQUEST_VALUES)) {
            inputsToRestore.set(new ArrayList<UIInput>());
        }
    }

    /** {@inheritDoc} */
    public void afterPhase(PhaseEvent event) {
        // Restore the list directly after the validation phase.
        // No need to keep the component tree in an inconsistent
        // state any longer.
        if (event.getPhaseId().equals(PhaseId.PROCESS_VALIDATIONS)) {
            // Restore all.
            List<UIInput> list = inputsToRestore.get();
            while (!list.isEmpty()) {
                list.remove(0).setRequired(true);
            }

            // Cleanup ThreadLocal.
            inputsToRestore.remove();
        }
    }

    /** {@inheritDoc} */
    public PhaseId getPhaseId() {
        // This PhaseListener fires in two phases.
        return PhaseId.ANY_PHASE;
    }
}
